package com.itheima.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {


    // 程序入口
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取前端传递过来的方法名
            String action = request.getParameter("action");
            // 获取class字节码对象
            Class clazz = this.getClass();
            // 根据方法名获取方法对象
            Method declaredMethod = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            // 执行该方法
            declaredMethod.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    // 抽取返回json到客户端公共方法
    public void writeJsonToClient(Object object, HttpServletResponse response) throws ServletException, IOException {
        // 将对象转为json
        String json = new ObjectMapper().writeValueAsString(object);
        // 响应到客户端
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}